package com.jackrain.nea.ad.mapper;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 系统参数
 * @author Yvan
 */
@Mapper
public interface AdParamMapper {

    String FIELDS = "ID, AD_CLIENT_ID, AD_ORG_ID, NAME, DESCRIPTION, " +
            "VALUETYPE, PARMTYPE, VALUELIST, DEFAULTVALUE, VALUE, " +
            "OWNERID, CREATIONDATE, MODIFIERID, MODIFIEDDATE, ISACTIVE, " +
            "MODIFIERNAME, MODIFIERENAME, OWNERNAME, OWNERENAME";

    @Delete("delete from AD_PARAM where id = #{id}")
    int delete(Long id);

    @UpdateProvider(type = AdParamSql.class, method = "update")
    int update(JSONObject object);

    @InsertProvider(type = AdParamSql.class, method = "insert")
    int insert(JSONObject object);

    @Select("select " + FIELDS + " from AD_PARAM where id = #{id}")
    HashMap<String, Object> getById(Long id);

    @Select("select ID from AD_PARAM where NAME = #{name}")
    Long getIdByName(String name);

    @SelectProvider(type = AdParamSql.class, method = "queryList")
    ArrayList<HashMap<String, Object>> listByCondition(String condition, String order);

    class AdParamSql{
        public String update(JSONObject map) {
            return new SQL() {
                {
                    UPDATE("AD_PARAM");
                    for (String key : map.keySet()) {
                        if(!"ID".equals(key)){
                            SET(key + "= #{" + key + "}");
                        }
                    }
                    WHERE("ID = #{ID}");
                }
            }.toString();
        }

        public String insert(JSONObject map){
            return new SQL(){
                {
                    INSERT_INTO("AD_PARAM");
                    for (String key : map.keySet()){
                        VALUES(key, "#{" + key + "}");
                    }
                }
            }.toString();
        }

        public String queryList(String condition, String order){
            return new SQL(){
                {
                    SELECT(FIELDS);
                    FROM("AD_PARAM");
                    WHERE(condition);
                    ORDER_BY(order);
                }
            }.toString();
        }
    }
}
